#!/bin/bash

# Available environment:
BUILD_DIR=$TONE_BM_RUN_DIR/build
INSTALL_DIR="/usr/local/qemu-kvm"

# Default values
DEFAULT_IMAGE_PATH="/home/qemu-resource/aliyun_2_1903_x64_20G_alibase_20231221.qcow2"
DEFAULT_SSH_USER="root"
DEFAULT_SSH_PASS="beaker"

# Use environment variables or default values
IMAGE_PATH=${IMAGE_PATH:-$DEFAULT_IMAGE_PATH}
SSH_USER=${SSH_USER:-$DEFAULT_SSH_USER}
SSH_PASS=${SSH_PASS:-$DEFAULT_SSH_PASS}

VM_NAME="aliyun2_vm"
CONSOLE_LOG="console_output.log"
# LOG_FILE="${BUILD_DIR}/meson-logs/testlog.txt"
# UNITTEST_LOG_FILE="unittest_output.log"
RETRY_COUNT=3
SSH_HOST="localhost"
SSH_PORT=2222



run() {
    # Check and download the image
    if [ -n "$IMAGE_URL" ]; then
        echo "Downloading image from $IMAGE_URL..."
        wget -P /home/qemu-resource "$IMAGE_URL"
        
        FILENAME=$(basename "$IMAGE_URL")
        IMAGE_PATH="/home/qemu-resource/$FILENAME"
        echo "Image downloaded to $IMAGE_PATH"
    fi
    echo "Using IMAGE_PATH: $IMAGE_PATH"
    echo "Using SSH_USER: $SSH_USER"
    echo "Using SSH_PASS: $SSH_PASS"
    mkdir -p $BUILD_DIR
    cd $BUILD_DIR
    if ! ../configure --enable-slirp --target-list-exclude=loongarch64-softmmu --prefix="$INSTALL_DIR"; then
        echo "====FAIL: qemu-kvm-build"
        exit 1
    fi

    if make -j$(nproc); then
        echo "====PASS: qemu-kvm-build"
    else
        echo "====FAIL: qemu-kvm-build"
        exit 1
    fi
    make install
    
    # Verify installation
    if ! "$INSTALL_DIR/bin/qemu-system-x86_64" --version; then
        echo "QEMU installation failed"
        exit 1
    else 
        echo "====PASS: qemu-kvm-version"
    fi

    # # Run unit tests
    # make -j$(nproc) check 2>&1 | tee "$UNITTEST_LOG_FILE"
    
    # if [ -f "$LOG_FILE" ]; then
    #     echo "Meson log file found, performing statistical check..."
    #     # Extract statistics from log file
    #     OK_COUNT=$(grep -oP 'Ok:\s+\K\d+' $LOG_FILE)
    #     EXPECTED_FAIL_COUNT=$(grep -oP 'Expected Fail:\s+\K\d+' $LOG_FILE)
    #     FAIL_COUNT=$(grep -oP '^Fail:\s+\K\d+' $LOG_FILE)
    #     UNEXPECTED_PASS_COUNT=$(grep -oP 'Unexpected Pass:\s+\K\d+' $LOG_FILE)
    #     SKIPPED_COUNT=$(grep -oP 'Skipped:\s+\K\d+' $LOG_FILE)
    #     TIMEOUT_COUNT=$(grep -oP 'Timeout:\s+\K\d+' $LOG_FILE)
        
    #     # Check and print test results
    #     if [ "$FAIL_COUNT" -eq "$EXPECTED_FAIL_COUNT" ] && [ "$UNEXPECTED_PASS_COUNT" -eq 0 ]; then
    #         echo "====PASS: qemu-kvm-unittests"
    #     else
    #         echo "====FAIL: qemu-kvm-unittests"
    #     fi
        
    #     # Print statistics
    #     echo "Statistics:"
    #     echo "  Ok:                 $OK_COUNT"
    #     echo "  Expected Fail:      $EXPECTED_FAIL_COUNT"
    #     echo "  Fail:               $FAIL_COUNT"
    #     echo "  Unexpected Pass:    $UNEXPECTED_PASS_COUNT"
    #     echo "  Skipped:            $SKIPPED_COUNT"
    #     echo "  Timeout:            $TIMEOUT_COUNT"
    # else
    #     echo "Meson log file not found, checking standard output content..."
    #     if grep -iq "Passed all" "$UNITTEST_LOG_FILE"; then
    #         echo "====PASS: qemu-kvm-unittests"
    #     else
    #         echo "====FAIL: qemu-kvm-unittests"
    #     fi
    # fi

    # Start the virtual machine
    echo "Starting the virtual machine..."
    "$INSTALL_DIR/bin/qemu-system-x86_64" \
        -name $VM_NAME \
        -m 2048 \
        -smp 2 \
        -drive file=$IMAGE_PATH,format=qcow2 \
        -net nic -net user,hostfwd=tcp::2222-:22 \
        -nographic \
        -serial mon:stdio \
        -monitor telnet:127.0.0.1:55555,server,nowait \
        &> $CONSOLE_LOG &
    VM_PID=$!

    # Wait for the virtual machine to start
    sleep 10

    # Check if the virtual machine process is still running
    if ps -p $VM_PID > /dev/null
    then
        echo "Virtual machine started successfully, PID: $VM_PID"
    else
        echo "Virtual machine failed to start"
        cat $CONSOLE_LOG
        exit 1
    fi

    # Perform basic functionality verification
    echo "Performing basic functionality verification..."

    # Check if SSH is accessible
    echo "Checking SSH..."
    sleep 5
    if nc -zv localhost 2222 2>&1 | grep -i 'connected'
    then
        echo "SSH port check successful"
    else
        echo "SSH port check failed"
        kill $VM_PID
        exit 1
    fi

    RETRY=0
    while [ $RETRY -lt $RETRY_COUNT ]; do
        sshpass -p $SSH_PASS ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -p $SSH_PORT $SSH_USER@$SSH_HOST "echo 'qemu-kvm boot successful!' && uptime"
        if [ $? -eq 0 ]; then
            echo "Basic functionality verification passed"
            SSH_SUCCESS=true
            break
        else
            echo "SSH connection failed, retrying ($((RETRY + 1))/$RETRY_COUNT)..."
            SSH_SUCCESS=false
            RETRY=$((RETRY + 1))
            sleep 5
        fi
    done

    if [ "$SSH_SUCCESS" = true ]; then
        echo "====PASS: qemu-kvm-boot"
    else
        echo "====FAIL: qemu-kvm-bootgit"
        kill $VM_PID
        exit 1
    fi

    # Stop the virtual machine
    echo "Stopping the virtual machine..."
    kill $VM_PID
    echo "All tests completed"
    exit 0
}

parse() {
    $TONE_BM_SUITE_DIR/parse.awk
}

teardown() {
    rm -rf "$INSTALL_DIR"
}
